package com.simen.hellobytes.rpc.rmi;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.RMISocketFactory;

import javax.naming.NamingException;

public class RMIServerTest implements RMIServerSocketFactory {
    public static void main(String[] args) throws RemoteException, NamingException, MalformedURLException, AlreadyBoundException {
        System.out.println("Constructing server implementation");
        Warehouse centralWarehouse = new WarehouseImpl();

        System.out.println("Binding server implementation to registry");

        RMIClientSocketFactory csf = RMISocketFactory.getDefaultSocketFactory();
        RMIServerSocketFactory ssf = new RMIServerTest();
        //LocateRegistry.createRegistry(1099, null, ssf);

        LocateRegistry.createRegistry(1099);
        Naming.bind("rmi://localhost:1099/central_warehoues", centralWarehouse);

        System.out.println("Waiting for invocations from clients ...");
    }

    public ServerSocket createServerSocket(int port) throws IOException {
        // Tricky bit; make a server socket with bound address
        return new ServerSocket(port, 0, InetAddress.getLocalHost());
    }
}